import React, {useEffect, useState} from 'react';
import {
    Box,
    Button,
    Card,
    CardContent,
    CardHeader,
    Divider,
    FormControl,
    IconButton,
    InputLabel,
    MenuItem,
    Paper,
    Select, Stack,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TablePagination,
    TableRow,
    Tooltip
} from "@mui/material";
import CircularProgress from "@mui/material/CircularProgress";

import {del, list} from "../../api/school/class-group";
import {list as listCourse} from "../../api/info/course";
import ToggleButton from "@mui/material/ToggleButton";
import RefreshIcon from '@mui/icons-material/Refresh';
import SearchIcon from '@mui/icons-material/Search';
import AddIcon from '@mui/icons-material/Add';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import ExpandIcon from '@mui/icons-material/Expand';
import CompressIcon from '@mui/icons-material/Compress';
import HourglassFullIcon from '@mui/icons-material/HourglassFull';

import {RestartAlt} from "@mui/icons-material";

import LoadingButton from "@mui/lab/LoadingButton";

import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import PageNavBar from "../common/page-nav-bar";
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import CreateClassGroup from "./create-class-group";
import DeleteIcon from "@mui/icons-material/Delete";

import {confirm} from "../common/confirm";
import {alert} from "../common/alert";
import Typography from "@mui/material/Typography";

const defaultForm = Object.freeze({
    page: 1,
    courseId: 0,
    completed: false,
});

function ClassGroup() {

    const [total, setTotal] = useState(0);
    const [page, setPage] = useState(1);
    const [size, setSize] = useState(10);

    const [form, setForm] = useState({...defaultForm});

    const [loading, setLoading] = useState(false);
    const [classGroups, setClassGroups] = useState([]);

    const [courses, setCourses] = useState([]);

    const [searching, setSearching] = useState(false);
    const [showForm, setShowForm] = useState(true);
    const [dense, setDense] = useState(true);

    const [create, setCreate] = useState(false);

    function loadClassGroups(query) {
        setLoading(true);

        list(query).then(data => {

            setTotal(data.total);
            setPage(data.page);
            setSize(data.size);
            setClassGroups(data.list);

            setLoading(false);
            setSearching(false);
        });
    }

    function loadCourses() {
        listCourse().then(data => {
            setCourses(data);
        });
    }

    useEffect(() => {
        loadClassGroups(defaultForm);
        loadCourses();
    }, []);

    function handleChange(event) {
        const {name, value} = event.target;
        setForm({...form, [name]: value});
    }

    function deleteClassGroup(e) {
        confirm(`将要删除班级 【${e.name}】，你确定吗？\n温馨提示：删除已排课班级将导致数据混乱。`)
            .then(choice => choice ? del(e.id) : Promise.resolve(false))
            .then(data => {
                if (data) {
                    loadClassGroups(form);
                    alert(`班级 【${e.name}】 已删除`, 'success');
                }
            });
    }

    return (
        <Box p={4} display="flex" gap={4} flexDirection="column">
            <Card raised sx={{padding: 2, boxSizing: 'border-box', width: '100%'}}>
                <CardHeader
                    title={
                        <Stack direction="row" alignItems="center" spacing={1}>
                            <Typography variant="h5">班级</Typography>
                            {loading && <CircularProgress color="inherit" size={24}/>}
                        </Stack>
                    }
                    action={
                        <Box mr={1}>
                            <IconButton onClick={() => setShowForm(!showForm)}>
                                {showForm ? <VisibilityOffIcon/> : <VisibilityIcon/>}
                            </IconButton>

                            <IconButton onClick={() => setDense(!dense)}>
                                {dense ? <ExpandIcon/> : <CompressIcon/>}
                            </IconButton>

                            <IconButton onClick={() => loadClassGroups(form)}><RefreshIcon/></IconButton>

                            <IconButton onClick={() => setCreate(true)}><AddIcon/></IconButton>
                        </Box>
                    }/>

                <CardContent>
                    {showForm && <Box mb={4} display="flex" gap={2} alignItems="center" flexWrap="wrap">
                        <FormControl sx={{width: 160}} size="small">
                            <InputLabel>课程</InputLabel>
                            <Select value={form.courseId} label="课程" name="courseId" onChange={handleChange}>
                                <MenuItem value="0">选择课程</MenuItem>
                                <Divider/>
                                {courses.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                            </Select>
                        </FormControl>

                        <ToggleButtonGroup size="small" exclusive name="completed" value={form.completed}
                                           onChange={(_, newValue) => {
                                               setForm({...form, completed: newValue});
                                           }}>
                            <Tooltip title="未结课" placement="top" arrow>
                                <ToggleButton value={false}><HourglassFullIcon/></ToggleButton>
                            </Tooltip>
                            <Tooltip title="已结课" placement="top" arrow>
                                <ToggleButton value={true}><CheckCircleIcon/></ToggleButton>
                            </Tooltip>
                        </ToggleButtonGroup>

                        <Button startIcon={<RestartAlt/>} variant="contained" color="primary"
                                onClick={() => setForm({...defaultForm})}>
                            重置
                        </Button>
                        <LoadingButton startIcon={<SearchIcon/>} variant="contained" color="primary"
                                       type="submit" loading={searching}
                                       loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                       onClick={() => {
                                           setSearching(true);

                                           const updatedForm = {...form, page: 1};
                                           setForm(updatedForm);
                                           loadClassGroups(updatedForm);
                                       }}>
                            查询
                        </LoadingButton>
                    </Box>}

                    <TableContainer component={Paper}>
                        <Table size={dense ? 'small' : 'medium'}>
                            <TableHead>
                                <TableRow>
                                    <TableCell width={'30px'}>ID</TableCell>
                                    <TableCell width={'120px'}>名称</TableCell>
                                    <TableCell width={'120px'}>课程</TableCell>
                                    <TableCell>学员</TableCell>
                                    <TableCell width={'30px'} align={"center"}>状态</TableCell>
                                    <TableCell width={'80px'} align={"center"}>已核销课时</TableCell>
                                    <TableCell width={'60px'} align={"center"}>下一课时</TableCell>
                                    <TableCell width={'40px'} align={"center"}>操作</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {classGroups.map(e => (
                                    <TableRow key={e.id}>
                                        <TableCell component="th" scope="row">{e.id}</TableCell>
                                        <TableCell>{e.name}</TableCell>
                                        <TableCell>{e.course?.name}</TableCell>
                                        <TableCell>{e.students.map(s => s.name).join('， ')}</TableCell>
                                        <TableCell align={'center'}>
                                            {e.completed ? <CheckCircleIcon/> : <HourglassFullIcon/>}
                                        </TableCell>
                                        <TableCell align={'center'}>{e.confirmedLessons}</TableCell>
                                        <TableCell align={'center'}>{e.nextLessonNumber}</TableCell>
                                        <TableCell align={'center'}>
                                            <IconButton disabled={e.confiremdLessons > 0 || e.nextLessonNumber > 1}
                                                        onClick={() => deleteClassGroup(e)} size="small">
                                                <DeleteIcon/>
                                            </IconButton>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                    {total > size && <TablePagination
                        ActionsComponent={PageNavBar}
                        rowsPerPageOptions={[10]}
                        component="div"
                        count={total}
                        rowsPerPage={size}
                        page={page - 1}
                        labelDisplayedRows={
                            ({count, page}) =>
                                `第 ${page + 1} 页，共 ${Math.ceil(total / size)} 页，共 ${count} 条数据`
                        }
                        onPageChange={(event, newPage) => {
                            window.scrollTo(0, 0);
                            const updatedForm = {...form, page: newPage + 1};
                            setForm(updatedForm);
                            loadClassGroups(updatedForm);
                        }}
                    />}
                </CardContent>
            </Card>

            <CreateClassGroup open={create} onClose={() => setCreate(false)}/>

        </Box>
    );
}

export default ClassGroup;
